package com.yl.androidutilscenter.http

import com.google.gson.Gson
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**

 */

/**
 *  * @author
 *  * @description: Retrofit类的封装
 *  * @date :2024/3/13
 *  * @version 1.0.0
 *
 *  下面是使用方式示例：
 * //双重校验锁式-单例 封装NetApiService 方便直接快速调用简单的接口
 * val myApiService: MyApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
 *     MyRetrofitUtilUtil.INSTANCE.getApi(MyApiService::class.java, MyApiService.SERVER_URL)
 * }
 * class MyRetrofitUtilUtil:BaseRetrofitUtil() {
 *
 *     companion object {
 *         val INSTANCE: MyRetrofitUtilUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
 *             MyRetrofitUtilUtil()
 *         }
 *     }
 *      override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
 *         super.setHttpClientBuilder(builder)
 *         return builder
 *     }
 *
 *     override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
 *
 *         return builder
 *     }
 * }
 */
 abstract class YLBaseRetrofitUtil {

    /**
     * @param serviceClass
     * @param baseUrl  baseurl
     *
     */
    fun <T> getApi(serviceClass: Class<T>, baseUrl: String): T {
        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
        return setRetrofitBuilder(retrofitBuilder).build().create(serviceClass)
    }

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     * 默认已添加日志拦截器
     */
    open fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        builder.addInterceptor(LogInterceptor())
        return builder
    }

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，Protocol
     * 默认已添加gson转换器
     */
    open fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        builder.addConverterFactory(GsonConverterFactory.create(Gson()))
        return builder
    }

    /**
     * 配置http
     */
    private val okHttpClient: OkHttpClient
        get() {
            return setHttpClientBuilder(OkHttpClient.Builder()).build()
        }


}